﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCS.Core.Models;
using System.Linq.Expressions;
using SCSService;
using SCS.Core.ViewModels;
using System.IO;


namespace SCS.Core.Controllers
{
    public class CampaignController : BaseController
    {
        public ActionResult Index()
        {
            return RedirectToAction("NewCampaign");
        }
        //private static readonly Logger Logger = LogManager.GetLogger("campaignLog");

        public ActionResult NewCampaign(string result)
        {
            if (Session["UserID"] == null)
            {
                return Redirect("../User/SignIn");
            }
            else
            {
                if (result != null)
                {
                    ViewData["old"] = result;
                }
                return View();
            }

        }

        //[ChildActionOnly]
        //public ActionResult CampaignCreateDetails()
        //{
        //    var campaignCreate = new Models.Collection.CreateCampaignCollection();
            
        //    ViewData["IsAdd"] = true;

        //    ViewData["ListClientDrop"] = new SelectList(Models.CampaignModels.GetListClientToDrop(), "ClientID", "Name");
        //    ViewData["ListAplinkStaffDrop"] = new SelectList(Models.UserModels.GetListUserNotPaging(), "UserID", "UserName");

        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/CampaignDetails", campaignCreate);
        //    }
        //}

        [ChildActionOnly]
        public ActionResult CampaignCreateMailSetting()
        {

            var campaignCreate = new Models.Collection.CreateCampaignCollection();

            ViewData["IsAdd"] = true;

            ViewData["ListMailSettingToDrop"] = new SelectList(Models.CampaignModels.GetListMailSettingToDrop(), "CampaignID", "ServerMail");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
            {
                return PartialView("../UserControl/MailSettingDetails", campaignCreate);
            }
        }

        [ChildActionOnly]
        public ActionResult CampaignCreateAttachFile()
        {
            var campaignCreate = new Models.Collection.CreateCampaignCollection();

            ViewData["IsAdd"] = true;

            if (Session["UserID"] == null)
            {
                return Redirect("../User/SignIn");
            }
            else
            {
                return PartialView("../UserControl/AttachFileDetails", campaignCreate);
            }
        }

        //[ChildActionOnly]
        //public ActionResult CampaignCreateTemplate()
        //{
        //    var campaignCreate = new Models.Collection.CreateCampaignCollection();

        //    ViewData["IsAdd"] = true;

        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/TemplateDetails", campaignCreate);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignCreateCustomerList()
        //{
        //    var campaignCreate = new Models.Collection.CreateCampaignCollection();

        //    ViewData["IsAdd"] = true;
        //    ViewData["ListContry"] = new SelectList(Models.CampaignModels.GetListContry(), "CountryID", "CountryName"); ;
        //    ViewData["ListTypeCustomer"] = new MultiSelectList(Models.CampaignModels.GetListTypeCustomer(), "TypeCustomerID", "TypeName");
            
        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/CustomerDetail", campaignCreate);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignCreateSchedule()
        //{
        //    var campaignCreate = new Models.Collection.CreateCampaignCollection();

        //    ViewData["IsAdd"] = true;
        //    ViewData["ListScheduleToDrop"] = new SelectList(Models.CampaignModels.GetListScheduleToDrop(), "ScheduleID", "ScheduleName");

        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/ScheduleDetail", campaignCreate);
        //    }
        //}

        //[HttpPost]
        //public JsonResult testty(List<string> ids)
        //{
        //    //string name, string adress, string phone, string mobile, byte status, int countryID, string Email1, string Email2, string Email3, string arrTypeCustomerID
        //    string arrEmailID = "";
        //    int cusID = 0;

        //    //Insert Email for customer
        //    //Default insert 3 email customer

        //    if (ids[6]!=string.Empty && ids[6]!=null)
        //    {
        //        MailBroadcastDataAcess.Entity.EmailCustomer email = new EmailCustomer();
        //        email.EmailAddress = ids[6].ToString();
        //        email.Status = 1;
        //        email.CustomerID = null;

        //        int id1 = Models.CampaignModels.CreateEmailCustomer(email);

        //        if (id1 > 0)
        //            arrEmailID += id1 + ",";
        //    }

        //    if (ids[7] != null && ids[7] != string.Empty)
        //    {
        //        MailBroadcastDataAcess.Entity.EmailCustomer email = new EmailCustomer();
        //        email.EmailAddress = ids[7].ToString();
        //        email.Status = 1;
        //        email.CustomerID = null;

        //        int id2 = Models.CampaignModels.CreateEmailCustomer(email);

        //        if (id2 > 0)
        //            arrEmailID += id2 + ",";
        //    }

        //    if (ids[8] != null && ids[8] != string.Empty)
        //    {
        //        MailBroadcastDataAcess.Entity.EmailCustomer email = new EmailCustomer();
        //        email.EmailAddress = ids[8].ToString();
        //        email.Status = 1;
        //        email.CustomerID = null;

        //        int id3 = Models.CampaignModels.CreateEmailCustomer(email);

        //        if (id3 > 0)
        //            arrEmailID += id3;
        //    }

        //    if (arrEmailID.EndsWith(","))
        //    {
        //        int index = arrEmailID.LastIndexOf(",");
        //        arrEmailID= arrEmailID.Substring(0, index);
        //    }

        //    //Insert Customer
        //    MailBroadcastDataAcess.Entity.Customer cus = new Customer();
        //    cus.CustomerName = ids[0].ToString();
        //    cus.Address = ids[1].ToString();
        //    cus.Phone = ids[2].ToString();
        //    cus.Mobile = ids[3].ToString();
        //    if (ids[4] != null)
        //    {
        //        cus.Status = byte.Parse(ids[4]);
        //    }
        //    if (ids[5] != null)
        //    {
        //        cus.CountryID = int.Parse(ids[5]);
        //    }

        //    cus.CustomerCampaignID = null;

        //    cusID = Models.CampaignModels.CreateCustomer(cus);

        //    if (cusID > 0)
        //    {
        //        var arr = ids[9].ToString().Split(',');
        //        for (int i = 0; i < arr.Length; i++)
        //        {
        //            //Create TypeCustomerManage

        //            if (arr[i] != string.Empty)
        //            {
        //                MailBroadcastDataAcess.Entity.TypeCustomerManage mana = new TypeCustomerManage();
        //                if (ids[5] != null)
        //                {
        //                    mana.CountryID = int.Parse(ids[5]);
        //                }

        //                mana.CustomerID = cusID;
        //                mana.TypeCustomerID = int.Parse(arr[i].ToString());

        //                Models.CampaignModels.CreateTypeCustomerManage(mana);
        //            }
        //            else
        //            {

        //            }
        //        }

        //        //Update CustomerID cho cac email ben tren
        //        var arr2 = arrEmailID.Split(',');
        //        for (int i = 0; i < arr2.Length; i++)
        //        {
        //            if (arr2[i] != string.Empty)
        //            {
        //                MailBroadcastDataAcess.Entity.EmailCustomer emailU = Models.CampaignModels.GetEmailCustomerByID(int.Parse(arr2[i]));
        //                emailU.CustomerID = cusID;
        //                emailU.EmailID = emailU.EmailID;
        //                emailU.EmailAddress = emailU.EmailAddress;
        //                emailU.Status = emailU.Status;

        //                Models.CampaignModels.UpdateEmailCustomer(emailU);
        //            }
        //        }
        //    }
        //    else
        //    {
        //        //Xoa het cac email cua khach hang nay vua tao
        //        var arr2 = arrEmailID.Split(',');
        //        for (int i = 0; i < arr2.Length; i++)
        //        {
        //            if (arr2[i] != string.Empty)
        //            {
        //                Models.CampaignModels.DelteEmailCustomerByID(int.Parse(arr2[i].ToString()));
        //            }
        //        }
        //    }
        //    return Json(cusID);
        //}

        ////[ChildActionOnly]
        ////[HttpPost]
        //public JsonResult GetCountryOptions()
        //{
        //    try
        //    {
        //        var country = Models.CampaignModels.GetListContry().Select(c => new { DisplayText = c.CountryName, Value = c.CountryID });
        //        return Json(new { Result = "OK", Options = country });
        //    }
        //    catch (Exception ex)
        //    {
        //        return Json(new { Result = "ERROR", Message = ex.Message });
        //    }
        //}

        //[HttpPost]
        //public ActionResult UploadCustomerFile(HttpPostedFileBase file)
        //{
        //    string path = "";

        //    if (file != null && file.ContentLength > 0)
        //    {
        //        if (Path.GetExtension(file.FileName).Contains("xls") || Path.GetExtension(file.FileName).Contains("xlsx"))
        //        {
        //            var fileName = Path.GetFileName(file.FileName);
        //            path = Path.Combine(Server.MapPath("../CustomerFiles"), fileName);
        //            file.SaveAs(path);
        //        }
        //        else
        //        {
        //        }
        //    }

        //    return this.Json(path);
        //}

        //public JsonResult GetListStaffByClientID(string id)
        //{
          
        //        List<MailBroadcastDataAcess.Entity.Staff> listStaff = new List<MailBroadcastDataAcess.Entity.Staff>();
                
        //        if (id != string.Empty)
        //        {
        //            listStaff = Models.CampaignModels.GetListStaffByClientID(int.Parse(id));
        //        }
        //        else
        //        { 
                    
        //        }

        //        var listresult = listStaff.Select(d => d.StaffID.ToString() + "|" + d.StaffName).Distinct().ToList();

        //        return this.Json(listresult);
           
        //}      

        public JsonResult GetMailSettingByID(string id)
        {

            Customer_Email_Campaign mailsetting = new Customer_Email_Campaign();
            if (id != null)
            {
                if (id != string.Empty)
                {
                    mailsetting = Models.CampaignModels.GetMailSettingByID(int.Parse(id));
                }

            }
            string result = "";

            if (mailsetting != null)
            {
                result += mailsetting.CampaignID + "|";
                if (mailsetting.ServerMail != null)
                {
                    result += mailsetting.ServerMail + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (mailsetting.CampaignName != null)
                {
                    result += mailsetting.CampaignName + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (mailsetting.PassSend != null)
                {
                    result += mailsetting.PassSend + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (mailsetting.SMTPPort != null)
                {
                    result += mailsetting.SMTPPort + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (mailsetting.TemplateID != null)
                {
                    result += mailsetting.TemplateID + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (mailsetting.SiteGuid != null)
                {
                    result += mailsetting.SiteGuid + "|";
                }
                else
                {
                    result += "" + "|";
                }

                if (mailsetting.EmailSend != null)
                {
                    result += mailsetting.EmailSend + "|";
                }
                else
                {
                    result += "" + "|";
                }

            }

            return this.Json(result);

        }

        //public JsonResult GetScheduleByID(string id)
        //{

        //    MailBroadcastDataAcess.Entity.Schedule schedule = new Schedule();
        //    if (id != null)
        //    {
        //        if (id != string.Empty)
        //        {
        //            schedule = Models.CampaignModels.GetScheduleByID(int.Parse(id));
        //        }

        //    }
        //    string result = "";

        //    if (schedule != null)
        //    {
        //        result += schedule.ScheduleID + "|";
        //        if (schedule.ScheduleName != null)
        //        {
        //            result += schedule.ScheduleName + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (schedule.SendDate != null)
        //        {
        //            result += schedule.SendDate + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (schedule.SendMonth != null)
        //        {
        //            result += schedule.SendMonth + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (schedule.DateRun != null)
        //        {
        //            result += schedule.DateRun + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }
                           
        //    }

        //    return this.Json(result);

        //}

        //public JsonResult GetTemplateByID(string id)
        //{

        //    MailBroadcastDataAcess.Entity.TemplateHtml temp = new MailBroadcastDataAcess.Entity.TemplateHtml();

        //    if (id != string.Empty)
        //    {
        //        temp = Models.CampaignModels.GetTemplateByID(int.Parse(id));
        //    }
        //    else
        //    {

        //    }

        //    string result = "";

        //    if (temp != null)
        //    {
        //        result += temp.TempID + "|";
        //        if (temp.Name != null)
        //        {
        //            result += temp.Name + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (temp.Content != null)
        //        {
        //            result += temp.Content + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (temp.Status != null)
        //        {
        //            result += temp.Status + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (temp.UserCreate != null)
        //        {
        //            result += temp.UserCreate + "|";
        //        }
        //        else
        //        {
        //            result += "" + "|";
        //        }

        //        if (temp.Deploy != null)
        //        {
        //            result += temp.Deploy + "|";
        //        }
        //        else
        //            result = "" + "|";

        //        if (temp.DateCreate != null)
        //        {
        //            result += temp.DateCreate + "|";
        //        }
        //        else
        //            result += "" + "|";

        //    }

        //    return this.Json(result);

        //}
        ////[HttpPost]
        //public JsonResult GetListTemplate(int jtStartIndex=0, int jtPageSize=0)
        //{
        //    int Total=0;
        //    int currentPage = 1;
        //    if (jtStartIndex == 0)
        //    {
        //        currentPage = 1;
        //    }
        //    else
        //    {
        //        currentPage = (jtStartIndex / jtPageSize) + 1;
        //    }
        //    List<MailBroadcastDataAcess.Entity.TemplateHtml> listTemplate = new List<MailBroadcastDataAcess.Entity.TemplateHtml>();
        //    listTemplate = Models.CampaignModels.GetListTemplatePaging(out Total, currentPage, jtPageSize, null, null, null, null, null, null);

        //    return Json(new { Result = "OK", Records = listTemplate, TotalRecordCount = Total });
        //}

        //[HttpPost]
        //public JsonResult GetListCustomerByCustomerClientID(int jtStartIndex = 0, int jtPageSize = 0, int clientID=0)
        //{
        //    int Total = 0;
        //    int currentPage = 1;
        //    if (jtStartIndex == 0)
        //    {
        //        currentPage = 1;
        //    }
        //    else
        //    {
        //        currentPage = (jtStartIndex / jtPageSize) + 1;
        //    }
        //    List<MailBroadcastDataAcess.Entity.Customer> listCus = new List<MailBroadcastDataAcess.Entity.Customer>();
        //    listCus = Models.CampaignModels.GetListCustomerByClientID(out Total, currentPage, jtPageSize, clientID);

        //    return Json(new { Result = "OK", Records = listCus, TotalRecordCount = Total });
        //}

        //[HttpPost]
        //public JsonResult GetListCustomerInCampaign(int customerCampaignID,int jtStartIndex = 0, int jtPageSize = 0)
        //{
        //    int Total = 0;
        //    int currentPage = 1;
        //    if (jtStartIndex == 0)
        //    {
        //        currentPage = 1;
        //    }
        //    else
        //    {
        //        currentPage = (jtStartIndex / jtPageSize) + 1;
        //    }
            
        //    List<MailBroadcastDataAcess.Entity.Customer> listCus = new List<MailBroadcastDataAcess.Entity.Customer>();
        //    listCus = Models.CampaignModels.GetListCustomerInCampaign(out Total, currentPage, jtPageSize, customerCampaignID);

        //    return Json(new { Result = "OK", Records = listCus, TotalRecordCount = Total });
        //}
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddCampaignCreate(FormCollection collection)
        {
            var campaignCreate = new Models.Collection.CreateCampaignCollection();
            TryUpdateModel(campaignCreate);
                int? camID = 0;
                camID = campaignCreate.CampaignID_AttachFileDetail;
                int mailSettingID = 0;
                int scheduleID = 0;
                int cusCamID = 0;
                string Error = "";
                #region Save File Attach
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase file = Request.Files[i];
                    if(file!=null && file.ContentLength>0)
                    {
                        var FileName = Path.GetFileName(file.FileName);
                        var Part = Path.Combine(Server.MapPath("~/Files"),FileName);
                        file.SaveAs(Part);
                        Customer_Email_Attach_File AttachFile = new Customer_Email_Attach_File();
                        AttachFile.FileName = FileName;
                        AttachFile.FilePath = Part;
                        AttachFile.CampaignID = camID;

                        int attID = Models.CampaignModels.CreateAttachFile(AttachFile);
                    
                    }

                    
                }

                #endregion
                return View();
       }

                    

        //            if (campaignCreate.ArrayStaffClientID != null && campaignCreate.ArrayStaffClientID != string.Empty)
        //            {
        //                //Save Client Staff Campign (Create Staff Client receive CC mail)
        //                string[] arrClientStaffID = campaignCreate.ArrayStaffClientID.Split(',');

        //                for (int i = 0; i < arrClientStaffID.Length; i++)
        //                {
        //                    //Create ClientStaffCampaign
        //                    MailBroadcastDataAcess.Entity.ClientStaffCampaign csc = new ClientStaffCampaign();
        //                    //csc.ClientStaffCCID = 0;
        //                    csc.StaffID = int.Parse(arrClientStaffID[i]);
        //                    csc.CampaignID = camID;
        //                    csc.CreateDate = DateTime.Now;
        //                    csc.ModifiedLast = null;

        //                    Models.CampaignModels.CreateClientStaffCampaign(csc);
        //                    Logger.Info("Create ClientStaffCampaign :" + csc.ClientStaffCCID);
        //                }
        //            }
                    
                    
                    

        //            //Update Template to Content of Campaign
        //            MailBroadcastDataAcess.Entity.Campaign camp3 = Models.CampaignModels.GetCampaignByID(camID);
        //            if (campaignCreate.Content_TemplateDetailValueINOUT != null && campaignCreate.Content_TemplateDetailValueINOUT != "")
        //            {
        //                camp3.Content = campaignCreate.Content_TemplateDetailValueINOUT.Substring(6);

        //                Models.CampaignModels.UpdateCampaign(camp3);
        //                Logger.Info("Update Content Template for Campaign :" + campaignCreate.Content_TemplateDetailValueINOUT.Substring(6));
        //            }

        //            //schedule
        //            if (campaignCreate.ScheduleID_ScheduleDetail != null)
        //            {
        //                //Lua chon schedule cu neu thong so co thay doi thi Update schedule
        //                //Update Schedule
        //                scheduleID = (int)campaignCreate.ScheduleID_ScheduleDetail;
        //                var schedule = Models.CampaignModels.GetScheduleByID(scheduleID);

        //                schedule.ScheduleName = campaignCreate.ScheduleName_ScheduleDetail;
        //                schedule.SendDate = campaignCreate.SendDate_ScheduleDetail;
        //                schedule.SendMonth = campaignCreate.SendMonth_ScheduleDetail;
        //                schedule.DateRun = campaignCreate.DateRun_ScheduleDetail;

        //                Models.CampaignModels.UpdateSchedule(schedule);
        //                Logger.Info("Update Schedule :" + schedule.ScheduleID);
        //            }
        //            else
        //            {
        //                //Delete Schedule old
        //                //Create new Schedule
        //                MailBroadcastDataAcess.Entity.Schedule schedule = new Schedule();
        //                schedule.ScheduleName = campaignCreate.ScheduleName_ScheduleDetail;
        //                schedule.SendDate = campaignCreate.SendDate_ScheduleDetail;
        //                schedule.SendMonth = campaignCreate.SendMonth_ScheduleDetail;
        //                schedule.DateRun = campaignCreate.DateRun_ScheduleDetail;

        //                scheduleID = Models.CampaignModels.CreateScheduleDetail(schedule);
        //                Logger.Info("Create new Schedule :" + schedule.ScheduleID);

        //                //Update ScheduleID for Campaign
        //                MailBroadcastDataAcess.Entity.Campaign camp4 = Models.CampaignModels.GetCampaignByID(camID);
        //                camp4.ScheduleID = scheduleID;

        //                Models.CampaignModels.UpdateCampaign(camp4);
        //                Logger.Info("Update scheduleID for Campaign :" + scheduleID);
        //            }

        //            if (campaignCreate.ArrayStaffAplinkID != string.Empty && campaignCreate.ArrayStaffAplinkID != null)
        //            {
        //                //Save Staff APLINK has assign
        //                string[] arrStaffAPLINKID = campaignCreate.ArrayStaffAplinkID.Split(',');

        //                for (int i = 0; i < arrStaffAPLINKID.Length; i++)
        //                {
        //                    //Create AssignUser
        //                    MailBroadcastDataAcess.Entity.AssignUser ass = new AssignUser();
        //                    //ass.AssignID = 0;
        //                    ass.CampaignID = camID;
        //                    //ass.UserID = int.Parse(Session["UserID"].ToString());
        //                    ass.UserID = int.Parse(campaignCreate.ArrayStaffAplinkID[i].ToString());

        //                    int idStaffAPLINK = Models.CampaignModels.CreateAssignUser(ass);
        //                    Logger.Info("idStaffAPLINK :" + idStaffAPLINK);

        //                    //Send Email Alert for user Assiged this Campaign
        //                    if (idStaffAPLINK > 0)
        //                    {
        //                        var userStaffAPLINK = Models.UserModels.GetUserByID(int.Parse(campaignCreate.ArrayStaffAplinkID[i].ToString()));
        //                        MailBroadcastBussiness.BaseService baseSvc = new MailBroadcastBussiness.BaseService();
        //                        baseSvc.SendEmailAlert(userStaffAPLINK.Email, campaignCreate.Name_CampaignDetail, campaignCreate.DateRun_ScheduleDetail);
        //                        Logger.Info("send Email Alert ");
        //                    }
        //                }
        //            }

                    

        //            //Save List Customer Add to Campaign
        //            if (campaignCreate.ArrCusIDInCampaign != null && campaignCreate.ArrCusIDInCampaign != "")
        //            {
        //                string[] arrCusIDinCampaign = campaignCreate.ArrCusIDInCampaign.Split(',');

        //                for (int i = 0; i < arrCusIDinCampaign.Length; i++)
        //                {
        //                    MailBroadcastDataAcess.Entity.Customer customers = Models.CampaignModels.GetCustomerByID(int.Parse(arrCusIDinCampaign[i].ToString()));
        //                    customers.CustomerCampaignID = cusCamID;

        //                    Models.CampaignModels.UpdateCustomer(customers);
        //                }
        //            }

        //            //Reader file in Location fordel auto attach
        //            if (campaignCreate.ArrCusIDInCampaign != null && campaignCreate.ArrCusIDInCampaign != "")
        //            {
        //                string[] arrCusIDinCampaign = campaignCreate.ArrCusIDInCampaign.Split(',');

        //                for (int i = 0; i < arrCusIDinCampaign.Length; i++)
        //                {
        //                    MailBroadcastDataAcess.Entity.Customer customers = Models.CampaignModels.GetCustomerByID(int.Parse(arrCusIDinCampaign[i].ToString()));
        //                    customers.CustomerCampaignID = cusCamID;

        //                    if (campaignCreate.LocationFilesReport_AttachFileDetail != null && campaignCreate.LocationFilesReport_AttachFileDetail != string.Empty)
        //                    {
        //                        if (Directory.Exists(campaignCreate.LocationFilesReport_AttachFileDetail.TrimEnd().TrimStart()))
        //                        {
        //                            DirectoryInfo dir = new DirectoryInfo(campaignCreate.LocationFilesReport_AttachFileDetail.TrimEnd().TrimStart());
        //                            FileInfo[] filess = dir.GetFiles();
        //                            foreach (FileInfo file in filess)
        //                            {
        //                                if (file.Name.Contains(customers.ShortName.Trim().ToUpper()))
        //                                {
        //                                    //Create attach type =2 
        //                                    MailBroadcastDataAcess.Entity.AttachFile attch = new AttachFile();
        //                                    //attch.AttachID = 0;
        //                                    attch.FileExtend = Path.GetExtension(file.Name);
        //                                    attch.FileName = file.Name;
        //                                    attch.Location = campaignCreate.LocationFilesReport_AttachFileDetail+ "\"" + file.Name;
        //                                    attch.TypeMail = true;  //true is mail send
        //                                    attch.TypeAttach = 2;   //2 Is Attach file for only Customer;
        //                                    attch.CampaignID = camID;
        //                                }
        //                            }
                                   
        //                        }
        //                    }
        //                }
        //            }

                    

        //        }
        //        return RedirectToAction("ListCampaigns");
        //    }
        //    catch (Exception ex)
        //    {
        //        //return View(ex.Message);
        //        //return RedirectToAction("NewCampaign");
        //        return RedirectToAction("NewCampaign", new { result = ex.Message });
        //    }

        //}

        //public static string GetGridThClass(ViewDataDictionary<MailBroadcastCore.ViewModels.CampaignViewModels> viewData, string sortField)
        //{

        //    if ((string)viewData["SortField"] != sortField)
        //        return "";

        //    if ((string)viewData["SortDirection"] == "Asc")
        //        return "asc";

        //    return "desc";
        //}

        //public static string GetGridThOnClick(ViewDataDictionary<MailBroadcastCore.ViewModels.CampaignViewModels> viewData, string sortField)
        //{
        //    if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
        //        return "sort('" + sortField + "', 'Desc');";

        //    return "sort('" + sortField + "', 'Asc');";
        //}

        //public ActionResult ListCampaigns()
        //{
        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return View();
        //    }
        //}

        //[ChildActionOnly]
        //[AcceptVerbs(HttpVerbs.Get)]
        //public ActionResult ListCampaign(string NameSearch, int? StatusSearch, int? ClientIDSearch, int? UserCreateSearch)
        //{
        //    int currentPage = 1;
        //    int pageSize = 20;
        //    string sortField = "CampaignID";
        //    string sortDirection = "Desc";
           
        //    ViewData["currentPage"] = currentPage;
        //    ViewData["pageSize"] = pageSize;


        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //        return ListCampaign(NameSearch, StatusSearch, ClientIDSearch, UserCreateSearch, currentPage, pageSize, sortField, sortDirection, null);


        //}

        //[ChildActionOnly]
        //[AcceptVerbs(HttpVerbs.Post)]
        //[ValidateInput(false)]
        //public ActionResult ListCampaign(string NameSearch, int? StatusSearch, int? ClientIDSearch, int? UserCreateSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction)
        //{
            
        //    if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
        //        currentPage = 1;

        //    if (currentPage == null && gridAction == "CurrentPageChanged")
        //    {
        //        string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
        //        currentPage = int.Parse(strCurrentPage);
        //    }
        //    else if (currentPage == null)
        //    {
        //        currentPage = 1;
        //    }


        //    if (pageSize == null)
        //    {
        //        pageSize = 20;
        //    }

        //    ViewData["currentPage"] = currentPage;

        //    int TotalNumber = 0;
                      
        //    var query = Models.CampaignModels.GetListCampaignPaging(out TotalNumber,(int)currentPage,(int)pageSize,NameSearch,(byte?)StatusSearch,null,null,UserCreateSearch,null,null,null,ClientIDSearch,null).AsQueryable();

        //    if (!String.IsNullOrEmpty(sortField))
        //    {
        //        var param = Expression.Parameter(typeof(Campaign), "Campaign");
        //        var sortExpression = Expression.Lambda<Func<Campaign, object>>
        //                                (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

        //        if (sortDirection == "Asc")
        //            query = query.OrderBy(sortExpression);
        //        else
        //            query = query.OrderByDescending(sortExpression);
        //    }

        //    int totalPages = (int)Math.Ceiling((double)TotalNumber / (double)pageSize);

        //    UpdateSorterViewData(sortField, sortDirection);
        //    UpdatePagerViewData(totalPages, TotalNumber, (int)currentPage, (int)pageSize);

        //    var result = query.ToList();

        //    if (TotalNumber == 0)
        //        result = new List<MailBroadcastDataAcess.Entity.Campaign>();

        //    // Set up our ViewModel
        //    var viewModel = new MailBroadcastCore.ViewModels.CampaignViewModels
        //    {
        //        CampaignItems = result,
        //        NameSearch = NameSearch,
        //        StatusSearch = (byte?)StatusSearch,
        //        ClientIDSearch=ClientIDSearch,
        //        UserCreateSearch=UserCreateSearch
        //    };

        //    // Return the view
        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //        return PartialView("../UserControl/ListCampaign", viewModel);
        //}

        //public ActionResult ChangeStatusCampaign(int? id, int? newstatus)
        //{
        //    Models.CampaignModels.ChangeStatusCampaign(id, newstatus);

        //    string outStr = "" + newstatus;
        //    return Json(outStr);
        //}

        //public ActionResult DeleteCampaign(int id, string returnUrl)
        //{
        //    // 3 Is Status of campaign isdelete
        //    Models.CampaignModels.ChangeStatusCampaign(id,3);
            
        //    return Redirect(returnUrl);
        //}

        //public ActionResult EditCampaign(int? id)
        //{
        //    ViewData["CampaignID"] = id;

        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return View();
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignDetailsEdit(int? id)
        //{
        //    var campaignEdit = new Models.Collection.CreateCampaignCollection();
            
        //        var cam =id!=null? Models.CampaignModels.GetCampaignByID((int)id):new MailBroadcastDataAcess.Entity.Campaign();
                

        //        campaignEdit.Name_CampaignDetail = cam.Name;
        //        campaignEdit.Status_CampaignDetail = cam.Status;
        //        campaignEdit.ConfigID_CampaignDetail = cam.ConfigID;
        //        campaignEdit.Description_CampaignDetail = cam.Description;
        //        campaignEdit.UserCreate_CampaignDetail = cam.UserCreate;
        //        campaignEdit.Deploy_CampaignDetail = cam.Deploy;
        //        campaignEdit.ScheduleID_CampaignDetail = cam.ScheduleID;
        //        campaignEdit.Content_CampaignDetail = cam.Content;

        //        var listStaffCampaign = Models.CampaignModels.GetListClientStaffCampaign(id);
        //        IEnumerable<int> seleteds = listStaffCampaign.Where(p => p.StaffID != null).Select(p => (int)p.StaffID).ToList();

        //        string arrId = "";
        //        foreach (var item in listStaffCampaign)
        //        {
        //            arrId += item.StaffID + ",";
        //        }
        //        campaignEdit.ArrayStaffClientID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";
        //        ViewData["ArrayStaffClientID"] = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";


        //        var listAssignUser = Models.CampaignModels.GetListAssignUser(id);
        //        int idAssignUser = 0;

        //        if (listAssignUser.Count() > 0)
        //        {
        //            idAssignUser = (int)listAssignUser.FirstOrDefault().UserID;
        //            campaignEdit.ArrayStaffAplinkID = idAssignUser.ToString();
        //            ViewData["ListAplinkStaffDrop"] = new SelectList(Models.UserModels.GetListUserNotPaging(), "UserID", "UserName", idAssignUser);
        //        }
        //        else
        //        {
        //            ViewData["ListAplinkStaffDrop"] = new SelectList(Models.UserModels.GetListUserNotPaging(), "UserID", "UserName");
        //        }

        //        if (Models.CampaignModels.GetListCustomerCampaignByCampaignID(id ?? 0).Count() > 0)
        //        {
        //            int clientID = Models.CampaignModels.GetListCustomerCampaignByCampaignID((int)id).FirstOrDefault().ClientID != null ? (int)Models.CampaignModels.GetListCustomerCampaignByCampaignID((int)id).FirstOrDefault().ClientID : 0;
        //            if (clientID > 0)
        //            {
        //                campaignEdit.ClientID_CampaignDetail = clientID;
        //                ViewData["ListClientDrop"] = new SelectList(Models.CampaignModels.GetListClientToDrop(), "ClientID", "Name", clientID);
        //                ViewData["ListStaffClient"] = new MultiSelectList(Models.CampaignModels.GetListStaffByClientID(clientID), "StaffID", "StaffName");

        //            }

        //        }
        //        else
        //        {
        //            ViewData["ListClientDrop"] = new SelectList(Models.CampaignModels.GetListClientToDrop(), "ClientID", "Name");
        //            ViewData["ListStaffClient"] = new MultiSelectList(Models.CampaignModels.GetListStaffByClientID(0), "StaffID", "StaffName");
        //        }
                    
                    
            
        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/CampaignDetailsEdit", campaignEdit);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignMailSettingEdit(int? id)
        //{
        //    Models.Collection.CreateCampaignCollection campaignEdit = new Models.Collection.CreateCampaignCollection();
            
        //        var cam =id!=null? Models.CampaignModels.GetCampaignByID((int)id):new MailBroadcastDataAcess.Entity.Campaign();
                
        //        if (cam != null)
        //        {
        //            if (cam.ConfigID != null)
        //            {
        //                var mailSetting = Models.CampaignModels.GetMailSettingByID((int)cam.ConfigID);
        //                campaignEdit = new Models.Collection.CreateCampaignCollection();

        //                campaignEdit.SMTPServer_MailSettingDetail = mailSetting.SMTPServer;
        //                campaignEdit.UserName_MailSettingDetail = mailSetting.UserName;
        //                campaignEdit.Password_MailSettingDetail = mailSetting.Password;
        //                campaignEdit.SMTPPort_MailSettingDetail = mailSetting.SMTPPort;
        //                campaignEdit.MailboxStatus_MailSettingDetail = mailSetting.MailboxStatus;
        //                campaignEdit.SendInterval_MailSettingDetail = mailSetting.SendInterval;
        //                campaignEdit.POP3Port_MailSettingDetail = mailSetting.POP3Port;
        //                campaignEdit.ConfigID_MailSettingDetail = mailSetting.ConfigID;

        //                ViewData["ListMailSettingToDrop"] = new SelectList(Models.CampaignModels.GetListMailSettingToDrop(), "ConfigID", "SMTPServer", (int)cam.ConfigID);

        //            }
        //        }
        //        ViewData["ListMailSettingToDrop"] = new SelectList(Models.CampaignModels.GetListMailSettingToDrop(), "ConfigID", "SMTPServer");
            
            
        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/MailSettingDetailsEdit", campaignEdit);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignAttachFileEdit(int? id)
        //{
        //    Models.Collection.CreateCampaignCollection campaignEdit = new Models.Collection.CreateCampaignCollection();
            
        //        var cam =id!=null? Models.CampaignModels.GetCampaignByID((int)id):new MailBroadcastDataAcess.Entity.Campaign();
                

        //        if (cam != null)
        //        {
        //            var attachFile = Models.CampaignModels.GetListAttachFileByCampaignID(id);
        //            if (attachFile != null)
        //            {
        //                campaignEdit = new Models.Collection.CreateCampaignCollection();
        //                string arrId = "";
        //                foreach (var item in attachFile)
        //                {
        //                    arrId += item.AttachID + ",";
        //                }

        //                campaignEdit.ArrAttachID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";
        //                ViewData["ArrAttachIDRemove"] = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";

        //                if (attachFile.Count == 1)
        //                {
        //                    campaignEdit.DeleteAttachFile1 = false;
        //                }
        //                else if (attachFile.Count == 2)
        //                {
        //                    campaignEdit.DeleteAttachFile1 = false;
        //                    campaignEdit.DeleteAttachFile2 = false;
        //                }
        //                else if (attachFile.Count == 3)
        //                {
        //                    campaignEdit.DeleteAttachFile1 = false;
        //                    campaignEdit.DeleteAttachFile2 = false;
        //                    campaignEdit.DeleteAttachFile3 = false;
        //                }
        //            }
        //        }

            
        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/AttachFileDetailsEdit", campaignEdit);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignTemplateEdit(int? id)
        //{
        //    Models.Collection.CreateCampaignCollection campaignEdit = new Models.Collection.CreateCampaignCollection();
            
        //        var cam =id!=null? Models.CampaignModels.GetCampaignByID((int)id):new MailBroadcastDataAcess.Entity.Campaign();
                

        //        if (cam != null)
        //        {
        //            if (cam.Content != null)
        //            {
        //                campaignEdit.Content_TemplateDetailValueINOUT = cam.Content;
        //            }
        //        }
            

        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/TemplateDetailsEdit", campaignEdit);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignCustomerListEdit(int? id)
        //{
        //    var cam =id!=null? Models.CampaignModels.GetCampaignByID((int)id):new MailBroadcastDataAcess.Entity.Campaign();
        //    Models.Collection.CreateCampaignCollection campaignEdit = new Models.Collection.CreateCampaignCollection();
        //    List<MailBroadcastDataAcess.Entity.Customer> listCustomerInCampaignEdit = new List<Customer>();

        //    ViewData["cusCampaignID"] = 0;
        //    if (cam != null)
        //    {
        //        if (Models.CampaignModels.GetListCustomerCampaignByCampaignID(id??0).Count() > 0)
        //        {
        //            int cusCampaignID = Models.CampaignModels.GetListCustomerCampaignByCampaignID((int)id).FirstOrDefault().CustomerCampaignID;
        //            if (cusCampaignID > 0)
        //            {
        //                campaignEdit.CustomerCampaignID_CustomerDetail = cusCampaignID;
        //                ViewData["cusCampaignID"] = cusCampaignID;
        //            }
        //        }
        //    }
            

        //    ViewData["ListContry"] = new SelectList(Models.CampaignModels.GetListContry(), "CountryID", "CountryName"); ;
        //    ViewData["ListTypeCustomer"] = new MultiSelectList(Models.CampaignModels.GetListTypeCustomer(), "TypeCustomerID", "TypeName");


        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/CustomerDetailEdit", campaignEdit);
        //    }
        //}

        //[ChildActionOnly]
        //public ActionResult CampaignScheduleEdit(int? id)
        //{
        //    Models.Collection.CreateCampaignCollection campaignEdit = new Models.Collection.CreateCampaignCollection();

        //    var cam = id != null ? Models.CampaignModels.GetCampaignByID((int)id) : new MailBroadcastDataAcess.Entity.Campaign();

        //    if (cam != null)
        //    {
        //        if (cam.ScheduleID != null)
        //        {
        //            var schedule = Models.CampaignModels.GetScheduleByID((int)cam.ScheduleID);
        //            campaignEdit = new Models.Collection.CreateCampaignCollection();

        //            campaignEdit.ScheduleName_ScheduleDetail = schedule.ScheduleName;
        //            campaignEdit.SendDate_ScheduleDetail = schedule.SendDate;
        //            campaignEdit.SendMonth_ScheduleDetail = schedule.SendMonth;
        //            campaignEdit.DateRun_ScheduleDetail = schedule.DateRun;

        //            ViewData["ListScheduleToDrop"] = new SelectList(Models.CampaignModels.GetListScheduleToDrop(), "ScheduleID", "ScheduleName",(int)cam.ScheduleID);

        //        }
        //    }
        //    ViewData["ListScheduleToDrop"] = new SelectList(Models.CampaignModels.GetListScheduleToDrop(), "ScheduleID", "ScheduleName");


        //    if (Session["UserID"] == null)
        //    {
        //        return Redirect("../User/SignIn");
        //    }
        //    else
        //    {
        //        return PartialView("../UserControl/ScheduleDetailEdit", campaignEdit);
        //    }
        //}

        //[AcceptVerbs(HttpVerbs.Post)]
        //[ValidateInput(false)]
        //public ActionResult SaveEditCampaign(FormCollection collection, IEnumerable<HttpPostedFileBase> files)
        //{
        //    var campaignCreate = new Models.Collection.CreateCampaignCollection();
        //    TryUpdateModel(campaignCreate);

        //    int camID = campaignCreate.CampaignID__CampaignDetail??0;
        //    int mailSettingID = campaignCreate.ConfigID_MailSettingDetail??0;
        //    int scheduleID = campaignCreate.ScheduleID_ScheduleDetail ?? 0;
        //    int cusCamID = 0;
        //    string Error = "";
        //    try
        //    {

        //        //Check for Update Campaign Detail Infor
        //        if (campaignCreate.ArrayStaffClientID == "" || campaignCreate.ArrayStaffClientID == null)
        //        {
        //            //Choose Staff received maill CC
        //            Error = "Must choose Staff CC";
        //            //return RedirectToAction("EditCampaign");
        //        }

        //        if (campaignCreate.ArrayStaffAplinkID == "" || campaignCreate.ArrayStaffAplinkID == null)
        //        {
        //            //Choose Staff APLINK
        //            Error = "Must choose Staff APLINK";
        //            //return RedirectToAction("EditCampaign");
        //        }
        //        //Update Campaign detail
        //        if (camID != 0)
        //        {
        //            MailBroadcastDataAcess.Entity.Campaign cam = Models.CampaignModels.GetCampaignByID(camID);
        //            cam.Name = campaignCreate.Name_CampaignDetail;
        //            cam.Status = campaignCreate.Status_CampaignDetail;
        //            cam.ConfigID = campaignCreate.ConfigID_MailSettingDetail;
        //            cam.Content = campaignCreate.Content_TemplateDetailValueINOUT;      //For Update Templated Apply

        //            Models.CampaignModels.UpdateCampaign(cam);
        //        }

        //        //Update MailSetting
        //        if (mailSettingID != 0)
        //        {
        //            MailBroadcastDataAcess.Entity.MailSetting mailsetting = Models.CampaignModels.GetMailSettingByID(mailSettingID);
        //            mailsetting.SMTPServer = campaignCreate.SMTPServer_MailSettingDetail;
        //            mailsetting.UserName = campaignCreate.UserName_MailSettingDetail;
        //            mailsetting.Password = campaignCreate.Password_MailSettingDetail;
        //            mailsetting.SMTPPort = campaignCreate.SMTPPort_MailSettingDetail;
        //            mailsetting.MailboxStatus = campaignCreate.MailboxStatus_MailSettingDetail;

        //            Models.CampaignModels.UpdateMailSetting(mailsetting);
        //        }

        //        //Update Attach File
        //        //Delete file attach old

        //        var arrAttID= campaignCreate.ArrAttachIDRemove;
        //        if (arrAttID != null)
        //        {
        //            if (campaignCreate.DeleteAttachFile1 == true)
        //            {
        //                MailBroadcastDataAcess.Entity.AttachFile attFile = Models.CampaignModels.GetAttachFileByID(int.Parse(arrAttID.Split(',')[0]));
        //                Models.CampaignModels.DeleteAttachFile(attFile.AttachID);
        //            }
        //            if (campaignCreate.DeleteAttachFile2 == true)
        //            {
        //                MailBroadcastDataAcess.Entity.AttachFile attFile = Models.CampaignModels.GetAttachFileByID(int.Parse(arrAttID.Split(',')[1]));
        //                Models.CampaignModels.DeleteAttachFile(attFile.AttachID);
        //            }
        //            if (campaignCreate.DeleteAttachFile3 == true)
        //            {
        //                MailBroadcastDataAcess.Entity.AttachFile attFile = Models.CampaignModels.GetAttachFileByID(int.Parse(arrAttID.Split(',')[2]));
        //                Models.CampaignModels.DeleteAttachFile(attFile.AttachID);
        //            }
        //        }
                
        //        //Save new Attach File
        //        for (int i = 0; i < Request.Files.Count; i++)
        //        {

        //            if (i != (Request.Files.Count - 1))
        //            {
        //                //Save File Attach for Campaign
        //                HttpPostedFileBase file = Request.Files[i];
        //                if (file != null && file.ContentLength > 0)
        //                {

        //                    var fileName = Path.GetFileName(file.FileName);
        //                    var path = Path.Combine(Server.MapPath("~/Files"), fileName);
        //                    file.SaveAs(path);

        //                    MailBroadcastDataAcess.Entity.AttachFile attch = new AttachFile();
        //                    //attch.AttachID = 0;
        //                    attch.FileExtend = Path.GetExtension(file.FileName);
        //                    attch.FileName = fileName;
        //                    attch.Location = path;
        //                    attch.TypeMail = true;  //true is mail send
        //                    attch.TypeAttach = 1;   //1 Is Attach file for Campaign;
        //                    attch.CampaignID = camID;

        //                    int attID = Models.CampaignModels.CreateAttachFile(attch);
        //                }

        //            }
        //        }
        //        //Update Customer List
        //        //Customer checked in checkbox is remove form list Customer for this Campaign
        //        if (campaignCreate.ArrCusIDRemoveFormCampaign != string.Empty)
        //        {
        //            var arrRemoveStr = campaignCreate.ArrCusIDRemoveFormCampaign.Length > 1 ? campaignCreate.ArrCusIDRemoveFormCampaign.Substring(0, campaignCreate.ArrCusIDRemoveFormCampaign.LastIndexOf(',')) : "";
        //            var arrRemove = arrRemoveStr.Split(',');
        //            if (arrRemove != null)
        //            {
        //                foreach (var item in arrRemove)
        //                {
        //                    //Update Customer (remove CustomerCampaignID from customer)
        //                    MailBroadcastDataAcess.Entity.Customer customerUpdateCampaign = Models.CampaignModels.GetCustomerByID(int.Parse(item));
        //                    customerUpdateCampaign.CustomerCampaignID = null;

        //                    Models.CampaignModels.UpdateCustomer(customerUpdateCampaign);
        //                }
        //            }
        //        }
                

        //        //Create new Customer for Campaign

        //            //Save file last for Attach Customer list
        //        HttpPostedFileBase filess = Request.Files[Request.Files.Count];
        //            if (filess != null && filess.ContentLength > 0)
        //            {
        //                if (Path.GetExtension(filess.FileName).Contains("xls") || Path.GetExtension(filess.FileName).Contains("xlsx"))
        //                {
        //                    var fileName = Path.GetFileName(filess.FileName);
        //                    var path = Path.Combine(Server.MapPath("~/CustomerFiles"), fileName);
        //                    filess.SaveAs(path);

        //                    MailBroadcastDataAcess.Entity.AttachFile attch = new AttachFile();
        //                    //attch.AttachID = 0;
        //                    attch.FileExtend = Path.GetExtension(filess.FileName);
        //                    attch.FileName = fileName;
        //                    attch.Location = path;
        //                    attch.TypeMail = true;  //true is mail send
        //                    attch.TypeAttach = 3;   //3 Is Attach file for Customer List;
        //                    attch.CampaignID = camID;

        //                    int attID = Models.CampaignModels.CreateAttachFile(attch);
        //                    if (attID > 0)
        //                    {
        //                        //Call method copy Data from file to table temp
        //                        Models.CampaignModels.SaveDatatoTempTable("Sheet1", path, "YES", "TempData");
        //                        //Session["test"] = save;
        //                        //Test notcheck
        //                        //if (save > 0)
        //                        //{
        //                        //Copy data from table TempData to other Table
        //                        //Customer , EmailCustomer, TypeCustomerManage
        //                        //Return list CustomerID inserted

        //                        //Delete all customer in TempData affter copy

        //                        List<MailBroadcastDataAcess.Entity.CopyTempData> listCopy = Models.CampaignModels.GetListCopyDataTemp();

        //                        if (listCopy != null && listCopy.Count() > 0)
        //                        {
        //                            foreach (var j in listCopy)
        //                            {

        //                                MailBroadcastDataAcess.Entity.TempData tempdata = Models.CampaignModels.GetTempDataByID((int)j.Copycode);
        //                                //Create TypeCustomerManage
        //                                MailBroadcastDataAcess.Entity.TypeCustomerManage typemana = new TypeCustomerManage();
        //                                if (tempdata.CountryID != null)
        //                                {
        //                                    typemana.CountryID = tempdata.CountryID;
        //                                }

        //                                typemana.CustomerID = j.Id;
        //                                typemana.TypeCustomerID = tempdata.TypeCustomerID;

        //                                Models.CampaignModels.CreateTypeCustomerManage(typemana);

        //                                //Create Email for each customer inserted
        //                                if (tempdata != null)
        //                                {
        //                                    if (tempdata.Email1 != string.Empty && tempdata.Email1 != null)
        //                                    {
        //                                        MailBroadcastDataAcess.Entity.EmailCustomer email1 = new EmailCustomer();
        //                                        email1.CustomerID = j.Id;
        //                                        email1.EmailAddress = tempdata.Email1;
        //                                        email1.Status = 1;

        //                                        int id1 = Models.CampaignModels.CreateEmailCustomer(email1);
        //                                    }


        //                                    if (tempdata.Email2 != string.Empty && tempdata.Email2 != null)
        //                                    {
        //                                        MailBroadcastDataAcess.Entity.EmailCustomer email2 = new EmailCustomer();
        //                                        email2.CustomerID = j.Id;
        //                                        email2.EmailAddress = tempdata.Email2;
        //                                        email2.Status = 1;

        //                                        int id2 = Models.CampaignModels.CreateEmailCustomer(email2);

        //                                    }


        //                                    if (tempdata.Email3 != string.Empty && tempdata.Email3 != null)
        //                                    {
        //                                        MailBroadcastDataAcess.Entity.EmailCustomer email3 = new EmailCustomer();
        //                                        email3.CustomerID = j.Id;
        //                                        email3.EmailAddress = tempdata.Email3;
        //                                        email3.Status = 1;

        //                                        int id3 = Models.CampaignModels.CreateEmailCustomer(email3);

        //                                    }

        //                                }

        //                                //Update CustomerCampaignID for Customer in copy list
        //                                MailBroadcastDataAcess.Entity.Customer cusU = Models.CampaignModels.GetCustomerByID((int)j.Id);
        //                                cusU.CustomerCampaignID = cusCamID;

        //                                Models.CampaignModels.UpdateCustomer(cusU);


        //                            }
        //                        }


        //                        ViewData["Result"] = "Save " + listCopy.Count() + " Customer in file :" + fileName;

        //                        //Delete TempData
        //                        if (listCopy != null && listCopy.Count() > 0)
        //                        {
        //                            foreach (var j in listCopy)
        //                            {
        //                                Models.CampaignModels.DeleteTempData((int)j.Copycode);
        //                            }
        //                        }

        //                        //}
        //                    }
        //                }
        //                else
        //                {

        //                }

        //            }

        //            //Update schedule
        //            if (scheduleID != 0)
        //            {
        //                MailBroadcastDataAcess.Entity.Schedule schedule = Models.CampaignModels.GetScheduleByID(scheduleID);
        //                schedule.ScheduleName = campaignCreate.ScheduleName_ScheduleDetail;
        //                schedule.SendDate = campaignCreate.SendDate_ScheduleDetail;
        //                schedule.SendMonth = campaignCreate.SendMonth_ScheduleDetail;
        //                schedule.DateRun = campaignCreate.DateRun_ScheduleDetail;

        //                Models.CampaignModels.UpdateSchedule(schedule);
        //            }
              
        //        //return RedirectToAction("NewCampaign");
        //        return RedirectToAction("NewCampaign");
        //    }
        //    catch
        //    {
        //        return RedirectToAction("NewCampaign");
        //    }

        //}
    }
}
